//
//  ModifyPasswordView.swift
//  ZYA
//
//  Created by WB Zhou on 2017/4/12.
//  Copyright © 2017年 aowang. All rights reserved.
//

import UIKit
class ModifyPasswordVC: GlobalFormVC {
    
   
    
    var tf_password: UITextField!
   
    var tf_confirmPassword: UITextField!
 
    // 旧密码,新密码,密码强弱(仅渔美康)
    var confirmClick:((String, String, String)->())?
    // 默认6位字母加数字  还有8
    var validatePasswordType = "6"
    
    fileprivate var selfReference: ModifyPasswordVC?
    var force = false // 强制改不能关闭
    init(force:Bool,validatePasswordType:String = "6") {
        super.init(nibName: nil, bundle: nil)
        self.force = force
        self.validatePasswordType = validatePasswordType
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
            .roundType(.top)
           let v = KSFormHItem(title: "旧密码*",appearance:appe)
        v.setLineHidden(true)
        return v
    }()
    var item2 :KSFormHItem = {
        let appe = KSFormHAppear()
            
           let v = KSFormHItem(title: "新密码*",appearance:appe)
        return v
    }()
    var item3 :KSFormHItem = {
    
        let appe = KSFormHAppear()
            .roundType(checkPlatform(type: .yuMeiKang) ? .never : .bottom)
        let v = KSFormHItem(title: "确认密码*",appearance:appe)
        return v
    }()
    
    lazy var pwdStrengthView: PWDStrengthView = {
        let appe = KSFormHAppear()
            .roundType(.bottom)
            .contentHight(80)
        let v = PWDStrengthView.init(title: "密码强度", appearance: appe)
        v.initUI()
        return v
    }()
    
    var oldStr = ""
    var newStr = ""
    var confirmStr = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "修改密码"
      
        self.configView()
       self.configAction()
       self.configDataSource()
      
   }
   
   func configView() {
       if force {
          
      } else {
          self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .done, target: self, action: #selector(dismissVC))
  
      }
       bg.add(item1).add(item2).add(item3)
       
       if checkPlatform(type: .yuMeiKang) {
           bg.add(pwdStrengthView)
       }
    
       header.ks_height = bg.frame.maxY
     
       tableVw.tableFooterView = footSubmit
       
   
  
   
   }
   func configAction() {
    
       submitButton.button.addTouchUpInSideAction { _ in
           
           guard self.judgeNoNone() else {return}
           let vali = Validation()
           vali.expression(self.oldStr != self.newStr, msg: "新密码不能等于旧密码")

           vali.expression(self.newStr == self.confirmStr, msg: "两次新密码不一样")
           
           
           
           if self.validatePasswordType == "6" {
               vali.expression(self.newStr.validatePassword6(), msg: "需要6位以上数字加字母")
           } else {
               vali.expression(self.newStr.validatePassword8(), msg: checkPlatform(type: .yuMeiKang) ? "请输入8位以上密码,至少包含字母,数字或特殊符号(~@%^*_)中的2个" : "需要8位以上数字加字母")
           }
           
           
           guard vali.validate() else {
               return
           }
           
  
           if let closure = self.confirmClick {
               
               var isStrong = "0"
               
               if checkPlatform(type: .yuMeiKang) {
                   switch self.pwdStrengthView.pwdType {
                       case .none, .low:
                           isStrong = "0"
                           break
                       case .medium, .height:
                           isStrong = "1"
                           break
                   }
               }
               
               closure(self.oldStr, self.newStr, isStrong)
           }
       }
       item1.textValueChangeClo = { str in
           self.oldStr = str
       }
       item2.textValueChangeClo = { [unowned self] str in
           self.newStr = str
           
           
           if checkPlatform(type: .yuMeiKang) {
               
               if str.count == 0 {
                   self.pwdStrengthView.pwdType = .none
                   return
               }
               
               var specialTimes = 0
              
               var hasNumber = false
               var hasLetter = false
               var hasSymbol = false
               
               str.forEach { s in
                   
                   let checkStr = "\(s)"
                   
                   if checkStr.valiRagular("^[0-9]*$") {
                       hasNumber = true
                   } else if checkStr.valiRagular("^[a-zA-Z]") {
                       hasLetter = true
                   } else if checkStr.valiRagular("^[~@%^*#_]") {
                       hasSymbol = true
                   }
               }
               
               if hasNumber {
                   specialTimes += 1
               }
               if hasLetter {
                   specialTimes += 1
               }
               if hasSymbol {
                   specialTimes += 1
               }
               
               if specialTimes > 2 {
                   self.pwdStrengthView.pwdType = .height
               } else if specialTimes == 2 {
                   self.pwdStrengthView.pwdType = .medium
               } else {
                   self.pwdStrengthView.pwdType = .low
               }

           }
       }
       item3.textValueChangeClo = { str in
           self.confirmStr = str
       }
   }

   func configDataSource() {
 

    }
    
    
    
    func present() {
    
        let currentVC = RouterUtils.currentTopViewController()!
        self.modalPresentationStyle = .overFullScreen
        let vc1 = AWNavigationController(rootViewController: self)
        currentVC.present_FullScreen(to: vc1)
    }

   @objc func dismissVC() {
        self.dismiss(animated: true)
    }
    
 
  
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
 
}




final class PWDStrengthView: KSFormHItem {
    enum PWDStrengthType {
        case none, low, medium, height
    }
    
    var pwdType: PWDStrengthType = .low {
        didSet {
            switch pwdType {
                case .none:
                    statusLab.text = ""
                    lines.forEach { line in
                        line.extBgColor(color: .systemGray6)
                    }
                case .low:
                    statusLab.extText(text: "低")
                        .extTextColor(color: .systemRed)
                    for (idx, line) in lines.enumerated() {
                        line.extBgColor(color: idx < 1 ? .systemRed : .systemGray6)
                    }
                case .medium:
                    statusLab.extText(text: "中")
                        .extTextColor(color: .systemOrange)
                    for (idx, line) in lines.enumerated() {
                        line.extBgColor(color: idx < 2 ? .systemOrange : .systemGray6)
                    }
                case .height:
                    statusLab.extText(text: "高")
                        .extTextColor(color: .systemGreen)
                    lines.forEach { line in
                        line.extBgColor(color: .systemGreen)
                    }
            }
        }
    }
    
    private var lines = [UIView]()
    
    private let statusLab = UILabel().easy("", .systemRed, .systemFont(ofSize: 15, weight: .medium))
    
    func initUI() {
        extUserInteractionEnabled(enable: false)
        tpTitleLab.text = "密码强度"
        textView.extHidden(hidden: true)
        assistBtn.extHidden(hidden: true)
                
        let lineW = 50
        var index = 0
        while index < 3 {
            let line = UIView()
                .extBgColor(color: .systemGray6)
            lines.append(line)
            
            addSubview(line)
            line.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(81 + index*(lineW + 2))
                make.size.equalTo(CGSize(width: lineW, height: 10))
                make.centerY.equalTo(tpTitleLab)
            }
            
            index += 1
        }
        
        addSubview(statusLab)
        statusLab.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.height.centerY.equalTo(tpTitleLab)
            make.left.equalToSuperview().offset(81 + 3*(lineW + 2))
        }
        
        let tipLab = UILabel().easy("请输入8位以上密码，至少包含字母、数字或特殊符号(~@%$^*_)中的2个", UIColor(kshex: "999999"), .systemFont(ofSize: 13))
            .extNumberOfLines(lines: 2)
        addSubview(tipLab)
        tipLab.snp.makeConstraints { make in
            make.left.equalTo(tpTitleLab)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(tpTitleLab.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
    
    override func layoutTitle() {
        tpTitleLab.snp.makeConstraints { make in
            make.left.equalTo(self).offset(widgetLeading)
            make.height.equalTo(40)
            make.top.equalToSuperview()
            make.width.lessThanOrEqualTo(KSGlobal.screenW/2)
        }
    }
}
